package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by 柱子 on 2020/10/15 22:22   Jwt令牌拦截器
 */
//@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //判断是否为登录请求
        if (request.getURI().getPath().contains("/admin/login")) {
            //登录请求放行
            return chain.filter(exchange);
        }
        //获取请求头信息
        HttpHeaders headers = request.getHeaders();
        String jwtToken = headers.getFirst("token");
        System.out.println(jwtToken + "缺少令牌");

        //判断令牌是否为空
        if (StringUtils.isEmpty(jwtToken)) {
            //等于null  向客户端响应消息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //'401' : 'Unauthorized',  未经授权

            return response.setComplete(); //设置完成 返回响应
        }
        //令牌解析
        try {
            JwtUtil.parseJWT(jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
            //返回响应 未经授权 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
